"""开发计划数据库模型"""
from sqlalchemy import Column, String, Integer, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base
import uuid
from datetime import datetime, timezone


def generate_id(prefix: str) -> str:
    """生成 ID"""
    return f"{prefix}-{uuid.uuid4().hex[:8]}"


class Task(Base):
    """任务表"""
    __tablename__ = "tasks"
    
    id = Column(String(50), primary_key=True)
    name = Column(String(80), nullable=False)
    due = Column(String(20), nullable=False)  # 格式: YYYY-MM-DD
    status = Column(String(20), nullable=False, default="progress")  # progress, done, blocked
    risk = Column(String(200), default="")
    priority = Column(Integer, nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    archived_at = Column(DateTime(timezone=True), nullable=True)  # 归档时间，None 表示未归档
    
    # 关联阶段
    stages = relationship("Stage", back_populates="task", cascade="all, delete-orphan", order_by="Stage.created_at")
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "due": self.due,
            "status": self.status,
            "risk": self.risk or "",
            "priority": self.priority,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "archived_at": self.archived_at.isoformat() if self.archived_at else None,
            "stages": [stage.to_dict() for stage in self.stages]
        }


class Stage(Base):
    """任务阶段表"""
    __tablename__ = "stages"
    
    id = Column(String(50), primary_key=True)
    task_id = Column(String(50), ForeignKey("tasks.id", ondelete="CASCADE"), nullable=False)
    name = Column(String(50), nullable=False)
    completed = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    # 关联任务
    task = relationship("Task", back_populates="stages")
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "completed": self.completed,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class AgentConfig(Base):
    """Agent配置表"""
    __tablename__ = "agent_configs"
    
    id = Column(String(50), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(100), nullable=False, unique=True)
    description = Column(String(500), default="")
    system_prompt = Column(Text, nullable=False)
    model = Column(String(100), nullable=False)
    tools = Column(Text, nullable=False)
    agent_type = Column(String(20), nullable=False, default="langgraph")
    is_active = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        import json
        try:
            tools_list = json.loads(self.tools)
        except:
            tools_list = []
            
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "system_prompt": self.system_prompt,
            "model": self.model,
            "tools": tools_list,
            "agent_type": self.agent_type,
            "is_active": self.is_active,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class ModelConfig(Base):
    """模型配置表"""
    __tablename__ = "model_configs"
    
    id = Column(String(50), primary_key=True, default=lambda: str(uuid.uuid4()))
    api_key = Column(String(500), nullable=False)
    base_url = Column(String(500), nullable=False)
    model = Column(String(100), nullable=False)
    remark = Column(String(500), default="")
    is_disabled = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "api_key": self.api_key,
            "base_url": self.base_url,
            "model": self.model,
            "remark": self.remark,
            "is_disabled": self.is_disabled,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class ToolCategory(Base):
    """工具分类表"""
    __tablename__ = "tool_categories"
    
    id = Column(String(50), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(50), nullable=False, unique=True)
    description = Column(String(500), default="")
    sort_order = Column(Integer, default=0)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "sort_order": self.sort_order,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class ToolConfig(Base):
    """工具配置表"""
    __tablename__ = "tool_configs"
    
    id = Column(String(50), primary_key=True, default=lambda: str(uuid.uuid4()))
    key = Column(String(100), nullable=False, unique=True)
    name = Column(String(100), nullable=False)
    description = Column(String(500), default="")
    category = Column(String(50), nullable=False)
    is_enabled = Column(Boolean, default=True)
    sort_order = Column(Integer, default=0)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "key": self.key,
            "name": self.name,
            "description": self.description,
            "category": self.category,
            "is_enabled": self.is_enabled,
            "sort_order": self.sort_order,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }

